package com.hongyuan.sellfitness.base;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.databinding.BindingAdapter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.hongyuan.sellfitness.R;
import com.hongyuan.sellfitness.data.md5.BaseUtil;
import com.hongyuan.sellfitness.my_view.BarPercentView;
import com.hongyuan.sellfitness.my_view.GlideRoundTransform;
import com.hongyuan.sellfitness.my_view.VersionChangeView;
import com.hongyuan.sellfitness.my_view.nestedrecyclerview.FlowLayoutManager;
import com.hongyuan.sellfitness.my_view.nestedrecyclerview.NestedRecyclerView;
import com.hongyuan.sellfitness.my_view.nine_gridimg.NineGridImageView;
import com.hongyuan.sellfitness.ui.find.beans.PostDetailBean;
import com.hongyuan.sellfitness.ui.home.adapter.MarkTextAdapter;
import com.hongyuan.sellfitness.ui.home.beans.StoreInfoBean;
import com.hongyuan.sellfitness.ui.main.beans.CheckVersionBeans;
import com.hongyuan.sellfitness.utils.DensityUtil;
import com.hongyuan.sellfitness.utils.UseGlideImageLoader;
import com.luck.picture.lib.tools.ScreenUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.util.List;

public class MyBindingAdapter {

    @BindingAdapter(value = {"imageUrl", "defaultImg"}, requireAll = false)
    public static void bindImageUrl(ImageView view, Object imageUrl, Drawable defaultImg){
        if(BaseUtil.isValue(imageUrl)){
            Glide.with(view.getContext()).load(imageUrl).into(view);
        }else{
            if(defaultImg != null){
                Glide.with(view.getContext()).load(defaultImg).into(view);
            }else{
                Glide.with(view.getContext()).load(R.mipmap.fang_default).into(view);
            }
        }
    }

    @BindingAdapter("imageFile")
    public static void bindImageUrl(ImageView view, File imageFile){
        if(!BaseUtil.isValue(imageFile))return;

        Glide.with(view.getContext()).load(imageFile).into(view);
    }

    @BindingAdapter("bannerList")
    public static void bindBanner(Banner banner, List<String> mList){
        if(mList == null || mList.size() <= 0)return;

        banner.setImages(mList)
                .setImageLoader(new UseGlideImageLoader())
                .setDelayTime(3000)
                .isAutoPlay(true)
                .setBannerStyle(BannerConfig.CIRCLE_INDICATOR )
                .setIndicatorGravity(BannerConfig.CENTER)
                .start();
    }

    @BindingAdapter("setAdapterData")
    public static void bindFlowLayoutRec(NestedRecyclerView nestRec, List<StoreInfoBean.OsfBean> mList){
        FlowLayoutManager flowLayoutManager = new FlowLayoutManager();
        nestRec.setLayoutManager(flowLayoutManager);

        if(mList != null && mList.size() > 0){
            MarkTextAdapter adapter = new MarkTextAdapter();
            nestRec.setAdapter(adapter);
            adapter.setNewData(mList);
        }
    }

    @BindingAdapter("setWebContent")
    public static void bindWebView(WebView view,String des){
        if(!BaseUtil.isValue(des))return;

        view.loadDataWithBaseURL(null, getNewData(view.getContext(),des),"text/html", "utf-8",null);
    }


    /**
     * 设置img标签下的width为手机屏幕宽度，height自适应
     *
     * @param data html字符串
     * @return 更新宽高属性后的html字符串
     */
    private static String getNewData(Context context, String data) {
        Document document = Jsoup.parse(data);

        Elements pElements = document.select("p:has(img)");
        for (Element pElement : pElements) {
            pElement.attr("style", "text-align:center");
            pElement.attr("max-width", ScreenUtils.getScreenWidth(context) + "px")
                    .attr("height", "auto");
        }
        Elements imgElements = document.select("img");
        for (Element imgElement : imgElements) {
            //重新设置宽高
            imgElement.attr("max-width", "100%")
                    .attr("height", "auto");
            imgElement.attr("style", "max-width:100%;height:auto");
        }
        return document.toString();
    }

    @BindingAdapter(value = {"maxPress", "valuePress"}, requireAll = false)
    public static void bindBarPercentView(BarPercentView view,int maxPress,int valuePress){
        view.setValue(maxPress,valuePress);
    }

    @BindingAdapter("setSexImg")
    public static void bindSexImg(ImageView img,String sex){
        if("1".equals(sex)){
            img.setImageResource(R.mipmap.person_boby_mark_img);
        }else{
            img.setImageResource(R.mipmap.person_girl_mark_img);
        }
    }

    @BindingAdapter("setPraiseImg")
    public static void bindPraiseImg(ImageView img,int praise){
        if(praise == 0){
            img.setImageResource(R.mipmap.like_huise_img);
        }else{
            img.setImageResource(R.mipmap.like_chengse_img);
        }
    }

    @BindingAdapter("selcetImg")
    public static void bindSelectImg(ImageView img,boolean isSelect){
        if(isSelect){
            img.setImageResource(R.mipmap.yuanquanquan_select_img);
        }else{
            img.setImageResource(R.mipmap.yuanquanquan_no_select_img);
        }
    }

    @BindingAdapter("intImg")
    public static void bindIntImg(ImageView img,int imgId){
        img.setImageResource(imgId);
    }

    @BindingAdapter("changeHeightImg")
    public static void bindHeightImg(ImageView imgView,String imageUrl){
        if(!BaseUtil.isValue(imageUrl))return;

        //获取屏宽
        int windWith = DensityUtil.getColumnWhith(imgView.getContext(),44,2);

        try {
            //获取宽高并计算比例
            String whStr = imageUrl.substring((imageUrl.lastIndexOf("_")+1),imageUrl.lastIndexOf("."));
            String[] wh = whStr.split("x");
            float ratio = Float.valueOf(wh[0])/Float.valueOf(wh[1]);

            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) imgView.getLayoutParams();
            layoutParams.height = (int)(windWith/ratio);
            imgView.setLayoutParams(layoutParams);

        }catch (Exception e){
            e.printStackTrace();
        }

        //显示图片
        RequestOptions options = new RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL).transform(new GlideRoundTransform(6));
        Glide.with(imgView.getContext()).load(imageUrl).transition(DrawableTransitionOptions.withCrossFade()).apply(options).into(imgView);
    }

    @BindingAdapter("setIntText")
    public static void bindPraiseImg(TextView textView, int nums){
        textView.setText(String.valueOf(nums));
    }

    @BindingAdapter("setImgData")
    public static void bindNineGridImg(NineGridImageView imageView, List<PostDetailBean.CiBean> mList){
        imageView.setImagesData(mList);
    }

    @BindingAdapter("myBackground")
    public static void bindMyBg(View view, int bgId){
        view.setBackgroundResource(bgId);
    }

    @BindingAdapter("setAppChangeDate")
    public static void bindUpdateAppData(VersionChangeView view, CheckVersionBeans.InfoBean infoBean){
        if(infoBean != null && infoBean.getIs_new() == 1){
            view.startChange(infoBean);
        }else{
            return;
        }
    }
}
